/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bt;

import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.DataElement;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.ServiceRecord;

/**
 *
 * @author kszyh
 */
public class Connector {
    private Vector devs = new Vector();
    private static final int SERVICE_NAME_BASE_LANGUAGE = 0x0100;
    private BluetoothConnection[] btConnections;
    private BluetoothConnection[] btC;
    private boolean lock = true;
    
    // targets to hosty z ktorymi chcemy nawiazac polaczenie //
    public Connector(Vector targets){
        devs = targets;
    }

    public BluetoothConnection[] getCons(){
    return btC;
    }

    public void makeConnections(){
        MakeConnectionsThread t = new MakeConnectionsThread(devs);
        t.start();
    }

    public boolean checkLock(){
        return lock;
    }

    public void devicesConnected(BluetoothConnection[] connections){
        BTServer bts = new BTServer(connections, true);
        btC = connections;
        /*for(int i = 0; i< connections.length; i++){
        System.out.println("Local Name: " + connections[i].getLocalName());
        System.out.println("Remote Name: " + connections[i].getRemoteName());
        }*/
    }
    private class MakeConnectionsThread extends Thread{
        Vector selected;

       MakeConnectionsThread(Vector _selected){
        selected = _selected;
       }


        @Override
       public void run(){
            btConnections = new BluetoothConnection[selected.size()];

            try{
                lock = true;
                for(int i = 0; i<selected.size(); i++){
                 ServiceRecord sr = (ServiceRecord)selected.elementAt(i);
                 String connectionUrl = sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                 DataElement de = sr.getAttributeValue(SERVICE_NAME_BASE_LANGUAGE);
                 String rname = (String)de.getValue();
                 String localName = LocalDevice.getLocalDevice().getFriendlyName();
                 btConnections[i] = new BluetoothConnection(connectionUrl, localName, rname);
                 btConnections[i].writeString(localName);
                System.out.println("Połączony z: " + rname);
                
                }
               lock = false;
                }
            catch(IOException e) {
                System.out.println("Błąd IO podczas tworzenia wątku!");
            }
            devicesConnected(btConnections);
       }

    }


}
